package com.example.sicnuaccountingapp.ui.profile

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.sicnuaccountingapp.data.repository.UserRepository
import com.example.sicnuaccountingapp.utils.PreferencesManager
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class ProfileViewModel @Inject constructor(
    private val userRepository: UserRepository,
    private val preferencesManager: PreferencesManager
) : ViewModel() {

    private val _state = MutableStateFlow<ProfileUiState>(ProfileUiState.Loading)
    val state: StateFlow<ProfileUiState> = _state.asStateFlow()

    init {
        loadUserProfile()
    }

    private fun loadUserProfile() {
        viewModelScope.launch {
            try {
                _state.value = ProfileUiState.Loading
                userRepository.getUserById(preferencesManager.userId)
                    .collect { user ->
                        if (user != null) {
                            _state.value = ProfileUiState.Success(user)
                        } else {
                            _state.value = ProfileUiState.Error("用户不存在")
                        }
                    }
            } catch (e: Exception) {
                _state.value = ProfileUiState.Error(e.message ?: "加载失败")
            }
        }
    }

    fun updateProfile(username: String, email: String?, phone: String?) {
        viewModelScope.launch {
            try {
                _state.value = ProfileUiState.Loading
                val currentUser = (state.value as? ProfileUiState.Success)?.user
                    ?: throw IllegalStateException("No user found")
                
                val updatedUser = currentUser.copy(
                    username = username,
                    email = email,
                    phone = phone
                )
                userRepository.updateUser(updatedUser)
                _state.value = ProfileUiState.Success(updatedUser)
            } catch (e: Exception) {
                _state.value = ProfileUiState.Error(e.message ?: "更新失败")
            }
        }
    }

    fun changePassword(currentPassword: String, newPassword: String) {
        viewModelScope.launch {
            try {
                _state.value = ProfileUiState.Loading
                val currentUser = (state.value as? ProfileUiState.Success)?.user
                    ?: throw IllegalStateException("No user found")
                
                if (currentUser.password != currentPassword) {
                    _state.value = ProfileUiState.Error("当前密码错误")
                    return@launch
                }
                
                val updatedUser = currentUser.copy(password = newPassword)
                userRepository.updateUser(updatedUser)
                _state.value = ProfileUiState.Success(updatedUser)
            } catch (e: Exception) {
                _state.value = ProfileUiState.Error(e.message ?: "修改密码失败")
            }
        }
    }

    fun logout() {
        preferencesManager.clearLoginInfo()
        // TODO: 处理登出后的导航
    }
} 